<template>
	<view class="wrap">
		<u-skeleton rows="5" :loading="state.loading" :animate="true" v-if="state.loading"/>
		<form-run
			v-else
			approve
			:taskKey="data.taskKey"
			:form="data.form"
			:comps="data.comps"
			:dataValue="data.dataValue"
			@approve="onApprove"
			@close="onClose"
		/>
	</view>
</template>

<script lang="ts" setup>
import { onLoad } from "@dcloudio/uni-app"
import { reactive } from 'vue'
import { request } from '../../utils/request'

const state = reactive({ loading: false })
const data = reactive<{ form: Record<string, any>; comps: any[]; dataValue: any; taskKey: any; taskId: any, formInstanceId: any }>({} as any)

const getStructure = (id: string) => {
	state.loading = true	
	request.get(`/flw/form-instance/${id}`).then((resp: any) => {
		if (resp.success) {
			if (resp.data) {
				if (resp.data.formJson) {
					const json = JSON.parse(resp.data.formJson)
					data.form = json.form
					data.comps = json.comps
				}
				if (resp.data.formValue) {
					data.dataValue = JSON.parse(resp.data.formValue)
				}
			}
		}
		state.loading = false
	})	
}
	
onLoad((option) => {
	data.taskId = option.tid
	data.taskKey = option.tkey
	data.formInstanceId = option.fid
	getStructure(option.fid)
})

const onApprove = ({ flowParams, formValue }: any) => {
  const formInstance = {
    formValue,
    formInstanceId: data.formInstanceId
  }
  state.loading = true
  const params = { taskId: data.taskId, formInstance, variables: flowParams }
	request.post(`/flw/form-instance/approve`, params).then((resp: any) => {
    state.loading = false
    if (resp.success) {
			uni.showToast({
				title: '表单已提交'
			})
			onClose()
    }
  })
}

const onClose = () => {
	uni.navigateBack()
}

</script>

<style lang="scss" scoped>
</style>
